package alogrithm;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;


/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/18 21:12
 */
public class Print {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        if (pRoot == null) {
            return new ArrayList<>();
        }
        ArrayList<ArrayList<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        boolean isOrderLeft = true;

        while (!queue.isEmpty()) {
            Deque<Integer> deque = new LinkedList<>();
            int n = queue.size();
            for (int i = 0; i < n; ++i) {
                TreeNode tmp = queue.poll();
                if (isOrderLeft) {
                    deque.offerLast(tmp.val);
                } else {
                    deque.offerFirst(tmp.val);
                }
                if (tmp.left != null) {
                    queue.offer(tmp.left);
                }
                if (tmp.right != null) {
                    queue.offer(tmp.right);
                }
            }
            res.add(new ArrayList<>(deque));
            isOrderLeft = !isOrderLeft;
        }
        return res;
    }

    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;

        public TreeNode(int val) {
            this.val = val;

        }

    }
}
